<template>
  <div class="album-detail" v-if="album">
    <div class="detail-header">
      <div class="album-info">
        <div class="album-title">
          <el-button type="text" @click="goBack" class="back-button">
            <el-icon><ArrowLeft /></el-icon>
          </el-button>
          <h2>{{ album.name }}</h2>
        </div>
        <div class="album-description" v-if="album.description">
          {{ album.description }}
        </div>
        <div class="album-meta">
          <span class="photo-count">{{ photos.length }} 张照片</span>
          <span class="created-date">创建于 {{ formatDate(album.createdAt) }}</span>
        </div>
      </div>
      
      <div class="album-actions">
        <el-button @click="showAddPhotosDialog">
          <el-icon><Plus /></el-icon>
          添加照片
        </el-button>
        <el-dropdown trigger="click" @command="handleAlbumAction">
          <el-button>
            <el-icon><MoreFilled /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="edit">
                <el-icon><Edit /></el-icon>
                编辑相册
              </el-dropdown-item>
              <el-dropdown-item command="setCover">
                <el-icon><Picture /></el-icon>
                设置封面
              </el-dropdown-item>
              <el-dropdown-item command="export" divided>
                <el-icon><Download /></el-icon>
                导出相册
              </el-dropdown-item>
              <el-dropdown-item command="delete">
                <el-icon><Delete /></el-icon>
                删除相册
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    
    <div class="detail-content">
      <PhotoToolbar 
        v-if="photos.length > 0"
        :view-mode="viewMode"
        :grid-columns="gridColumns"
        :thumbnail-size="thumbnailSize"
        :sort-option="sortOption"
        :selection-mode="selectionMode"
        :selected-count="selectedPhotoIds.length"
        @view-mode-change="handleViewModeChange"
        @grid-columns-change="handleGridColumnsChange"
        @thumbnail-size-change="handleThumbnailSizeChange"
        @sort-change="handleSortChange"
        @selection-mode-toggle="handleSelectionModeToggle"
        @select-all="handleSelectAll"
        @deselect-all="handleDeselectAll"
        @invert-selection="handleInvertSelection"
        @add-to-album="handleAddToAlbum"
        @remove-from-album="handleRemoveFromAlbum"
        @delete="handleDeletePhotos"
      />
      
      <div class="photos-container" v-if="photos.length > 0">
        <!-- 网格视图 -->
        <div 
          v-if="viewMode === 'grid'" 
          class="photos-grid"
          :style="{ gridTemplateColumns: `repeat(${gridColumns}, 1fr)` }"
        >
          <div 
            v-for="photo in sortedPhotos" 
            :key="photo.id"
            class="photo-item"
            :class="{ 'photo-selected': isPhotoSelected(photo.id) }"
            @click="handlePhotoClick(photo)"
            @contextmenu="handlePhotoContextMenu($event, photo)"
          >
            <div class="photo-thumbnail" :style="{ height: `${thumbnailSize}px` }">
              <img 
                :src="getThumbnailUrl(photo)" 
                :alt="photo.fileName"
                loading="lazy"
              />
              <div class="photo-overlay" v-if="selectionMode">
                <el-checkbox 
                  :model-value="isPhotoSelected(photo.id)"
                  @change="togglePhotoSelection(photo.id)"
                  @click.stop
                />
              </div>
            </div>
            <div class="photo-info">
              <div class="photo-name" :title="photo.fileName">{{ photo.fileName }}</div>
              <div class="photo-date">{{ formatDate(photo.capturedAt || photo.createdAt) }}</div>
            </div>
          </div>
        </div>
        
        <!-- 列表视图 -->
        <div v-else-if="viewMode === 'list'" class="photos-list">
          <div 
            v-for="photo in sortedPhotos" 
            :key="photo.id"
            class="photo-list-item"
            :class="{ 'photo-selected': isPhotoSelected(photo.id) }"
            @click="handlePhotoClick(photo)"
            @contextmenu="handlePhotoContextMenu($event, photo)"
          >
            <div class="photo-thumbnail" :style="{ width: `${thumbnailSize}px`, height: `${thumbnailSize}px` }">
              <img 
                :src="getThumbnailUrl(photo)" 
                :alt="photo.fileName"
                loading="lazy"
              />
              <div class="photo-overlay" v-if="selectionMode">
                <el-checkbox 
                  :model-value="isPhotoSelected(photo.id)"
                  @change="togglePhotoSelection(photo.id)"
                  @click.stop
                />
              </div>
            </div>
            <div class="photo-details">
              <div class="photo-name" :title="photo.fileName">{{ photo.fileName }}</div>
              <div class="photo-meta">
                <span>{{ formatDate(photo.capturedAt || photo.createdAt) }}</span>
                <span>{{ formatFileSize(photo.fileSize) }}</span>
                <span v-if="photo.width && photo.height">{{ photo.width }} × {{ photo.height }}</span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 瀑布流视图 -->
        <div v-else-if="viewMode === 'masonry'" class="photos-masonry">
          <div 
            v-for="photo in sortedPhotos" 
            :key="photo.id"
            class="photo-masonry-item"
            :class="{ 'photo-selected': isPhotoSelected(photo.id) }"
            :style="getMasonryItemStyle(photo)"
            @click="handlePhotoClick(photo)"
            @contextmenu="handlePhotoContextMenu($event, photo)"
          >
            <div class="photo-thumbnail">
              <img 
                :src="getThumbnailUrl(photo)" 
                :alt="photo.fileName"
                loading="lazy"
              />
              <div class="photo-overlay" v-if="selectionMode">
                <el-checkbox 
                  :model-value="isPhotoSelected(photo.id)"
                  @change="togglePhotoSelection(photo.id)"
                  @click.stop
                />
              </div>
            </div>
            <div class="photo-info">
              <div class="photo-name" :title="photo.fileName">{{ photo.fileName }}</div>
              <div class="photo-date">{{ formatDate(photo.capturedAt || photo.createdAt) }}</div>
            </div>
          </div>
        </div>
      </div>
      
      <div v-else class="empty-photos">
        <el-empty description="相册中暂无照片">
          <el-button type="primary" @click="showAddPhotosDialog">
            添加照片
          </el-button>
        </el-empty>
      </div>
    </div>
    
    <!-- 添加照片对话框 -->
    <el-dialog
      v-model="addPhotosDialogVisible"
      title="添加照片到相册"
      width="800px"
    >
      <PhotoSelector
        v-if="addPhotosDialogVisible"
        :photos="allPhotos"
        :selected-ids="[]"
        @confirm="handleAddPhotos"
        @cancel="addPhotosDialogVisible = false"
      />
    </el-dialog>
    
    <!-- 设置封面对话框 -->
    <el-dialog
      v-model="setCoverDialogVisible"
      title="设置封面"
      width="800px"
    >
      <PhotoSelector
        v-if="setCoverDialogVisible"
        :photos="photos"
        :selected-ids="album.coverPhotoId ? [album.coverPhotoId] : []"
        @confirm="handleCoverSelected"
        @cancel="setCoverDialogVisible = false"
      />
    </el-dialog>
    
    <!-- 照片查看器 -->
    <PhotoViewer
      v-if="photoViewerVisible && currentPhoto"
      :photo="currentPhoto"
      :photos="sortedPhotos"
      :initial-index="currentPhotoIndex"
      @close="photoViewerVisible = false"
    />
  </div>
  <div v-else class="album-detail-empty">
    <el-empty description="相册不存在" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { 
  ElButton, 
  ElIcon, 
  ElDropdown, 
  ElDropdownMenu, 
  ElDropdownItem, 
  ElEmpty,
  ElDialog,
  ElCheckbox,
  ElMessage,
  ElMessageBox
} from 'element-plus';
import { 
  ArrowLeft, 
  Plus, 
  MoreFilled, 
  Edit, 
  Picture, 
  Download, 
  Delete 
} from '@element-plus/icons-vue';
import type { Album, Photo } from '@/types';
import { albumService } from '@/services/albumService';
import { photoService } from '@/services/photoService';
import PhotoToolbar from '@/components/PhotoToolbar.vue';
import PhotoSelector from '@/components/common/PhotoSelector.vue';
import PhotoViewer from '@/components/photo/PhotoViewer.vue';

const route = useRoute();
const router = useRouter();

// 相册信息
const album = ref<Album | null>(null);
// 相册中的照片
const photos = ref<Photo[]>([]);
// 所有照片（用于添加照片）
const allPhotos = ref<Photo[]>([]);

// 视图模式
const viewMode = ref<'grid' | 'list' | 'masonry'>('grid');
// 网格列数
const gridColumns = ref(4);
// 缩略图大小
const thumbnailSize = ref(200);
// 排序选项
const sortOption = ref<'date' | 'name' | 'size' | 'type'>('date');
// 选择模式
const selectionMode = ref(false);
// 选中的照片ID
const selectedPhotoIds = ref<string[]>([]);

// 对话框状态
const addPhotosDialogVisible = ref(false);
const setCoverDialogVisible = ref(false);

// 照片查看器
const photoViewerVisible = ref(false);
const currentPhoto = ref<Photo | null>(null);
const currentPhotoIndex = ref(0);

// 计算属性：排序后的照片
const sortedPhotos = computed(() => {
  const sorted = [...photos.value];
  
  switch (sortOption.value) {
    case 'date':
      return sorted.sort((a, b) => {
        const dateA = new Date(a.capturedAt || a.createdAt).getTime();
        const dateB = new Date(b.capturedAt || b.createdAt).getTime();
        return dateB - dateA; // 降序，最新的在前
      });
    case 'name':
      return sorted.sort((a, b) => a.fileName.localeCompare(b.fileName));
    case 'size':
      return sorted.sort((a, b) => b.fileSize - a.fileSize); // 降序
    case 'type':
      return sorted.sort((a, b) => {
        const extA = a.fileName.split('.').pop()?.toLowerCase() || '';
        const extB = b.fileName.split('.').pop()?.toLowerCase() || '';
        return extA.localeCompare(extB);
      });
    default:
      return sorted;
  }
});

// 检查照片是否被选中
const isPhotoSelected = (photoId: string) => {
  return selectedPhotoIds.value.includes(photoId);
};

// 切换照片选择状态
const togglePhotoSelection = (photoId: string) => {
  const index = selectedPhotoIds.value.indexOf(photoId);
  if (index === -1) {
    selectedPhotoIds.value.push(photoId);
  } else {
    selectedPhotoIds.value.splice(index, 1);
  }
};

// 获取瀑布流项目样式
const getMasonryItemStyle = (photo: Photo) => {
  if (!photo.width || !photo.height) {
    return {};
  }
  
  const aspectRatio = photo.width / photo.height;
  const itemWidth = 200; // 固定宽度
  const itemHeight = itemWidth / aspectRatio;
  
  return {
    width: `${itemWidth}px`,
    height: `${itemHeight}px`
  };
};

// 获取缩略图URL
const getThumbnailUrl = (photo: Photo) => {
  if (photo.thumbnailPath) {
    return `file://${photo.thumbnailPath}`;
  }
  return `file://${photo.filePath}`;
};

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '未知';
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  });
};

// 格式化文件大小
const formatFileSize = (bytes: number) => {
  if (!bytes) return '未知';
  
  const units = ['B', 'KB', 'MB', 'GB'];
  let size = bytes;
  let unitIndex = 0;
  
  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024;
    unitIndex++;
  }
  
  return `${size.toFixed(1)} ${units[unitIndex]}`;
};

// 加载相册信息
const loadAlbum = async () => {
  const albumId = route.params.id as string;
  
  try {
    album.value = await albumService.getAlbumById(albumId);
    if (!album.value) {
      ElMessage.error('相册不存在');
      router.push({ name: 'Albums' });
      return;
    }
  } catch (error) {
    ElMessage.error('加载相册信息失败');
    router.push({ name: 'Albums' });
  }
};

// 加载相册中的照片
const loadAlbumPhotos = async () => {
  if (!album.value) return;
  
  try {
    photos.value = await albumService.getAlbumPhotos(album.value.id);
  } catch (error) {
    ElMessage.error('加载相册照片失败');
  }
};

// 加载所有照片
const loadAllPhotos = async () => {
  try {
    allPhotos.value = await photoService.getPhotos();
  } catch (error) {
    console.error('加载照片列表失败:', error);
  }
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 处理相册操作
const handleAlbumAction = async (command: string) => {
  if (!album.value) return;
  
  switch (command) {
    case 'edit':
      router.push({
        name: 'AlbumEdit',
        params: { id: album.value.id }
      });
      break;
    case 'setCover':
      setCoverDialogVisible.value = true;
      break;
    case 'export':
      ElMessage.info('导出功能待实现');
      break;
    case 'delete':
      try {
        await ElMessageBox.confirm(
          `确定要删除相册 "${album.value.name}" 吗？`,
          '删除确认',
          {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning'
          }
        );
        
        await albumService.deleteAlbum(album.value.id);
        ElMessage.success('相册删除成功');
        router.push({ name: 'Albums' });
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除相册失败');
        }
      }
      break;
  }
};

// 显示添加照片对话框
const showAddPhotosDialog = () => {
  addPhotosDialogVisible.value = true;
};

// 处理添加照片
const handleAddPhotos = async (photoIds: string[]) => {
  if (!album.value) return;
  
  try {
    await albumService.addPhotosToAlbum(album.value.id, photoIds);
    
    // 重新加载相册照片
    await loadAlbumPhotos();
    
    ElMessage.success(`已添加 ${photoIds.length} 张照片到相册`);
    addPhotosDialogVisible.value = false;
  } catch (error) {
    ElMessage.error('添加照片失败');
  }
};

// 处理封面选择
const handleCoverSelected = async (photoIds: string[]) => {
  if (!album.value || photoIds.length === 0) return;
  
  try {
    await albumService.updateAlbum(album.value.id, {
      coverPhotoId: photoIds[0]
    });
    
    // 更新本地相册数据
    album.value.coverPhotoId = photoIds[0];
    
    ElMessage.success('封面设置成功');
    setCoverDialogVisible.value = false;
  } catch (error) {
    ElMessage.error('设置封面失败');
  }
};

// 处理照片点击
const handlePhotoClick = (photo: Photo) => {
  if (selectionMode.value) {
    togglePhotoSelection(photo.id);
  } else {
    currentPhoto.value = photo;
    currentPhotoIndex.value = sortedPhotos.value.findIndex(p => p.id === photo.id);
    photoViewerVisible.value = true;
  }
};

// 处理照片右键菜单
const handlePhotoContextMenu = (event: MouseEvent, photo: Photo) => {
  event.preventDefault();
  // 这里可以显示自定义的右键菜单
};

// 处理视图模式变化
const handleViewModeChange = (mode: 'grid' | 'list' | 'masonry') => {
  viewMode.value = mode;
};

// 处理网格列数变化
const handleGridColumnsChange = (columns: number) => {
  gridColumns.value = columns;
};

// 处理缩略图大小变化
const handleThumbnailSizeChange = (size: number) => {
  thumbnailSize.value = size;
};

// 处理排序变化
const handleSortChange = (option: 'date' | 'name' | 'size' | 'type') => {
  sortOption.value = option;
};

// 处理选择模式切换
const handleSelectionModeToggle = () => {
  selectionMode.value = !selectionMode.value;
  if (!selectionMode.value) {
    selectedPhotoIds.value = [];
  }
};

// 处理全选
const handleSelectAll = () => {
  selectedPhotoIds.value = photos.value.map(photo => photo.id);
};

// 处理取消全选
const handleDeselectAll = () => {
  selectedPhotoIds.value = [];
};

// 处理反选
const handleInvertSelection = () => {
  const allIds = photos.value.map(photo => photo.id);
  selectedPhotoIds.value = allIds.filter(id => !selectedPhotoIds.value.includes(id));
};

// 处理添加到其他相册
const handleAddToAlbum = () => {
  ElMessage.info('添加到其他相册功能待实现');
};

// 处理从相册中移除
const handleRemoveFromAlbum = async () => {
  if (!album.value || selectedPhotoIds.value.length === 0) return;
  
  try {
    await ElMessageBox.confirm(
      `确定要从相册中移除 ${selectedPhotoIds.value.length} 张照片吗？`,
      '移除确认',
      {
        confirmButtonText: '移除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await albumService.removePhotosFromAlbum(album.value.id, selectedPhotoIds.value);
    
    // 从本地照片列表中移除
    photos.value = photos.value.filter(photo => !selectedPhotoIds.value.includes(photo.id));
    
    // 清空选择
    selectedPhotoIds.value = [];
    
    ElMessage.success('照片已从相册中移除');
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('移除照片失败');
    }
  }
};

// 处理删除照片
const handleDeletePhotos = () => {
  ElMessage.info('删除照片功能待实现');
};

// 监听路由参数变化
watch(() => route.params.id, () => {
  if (route.name === 'AlbumDetail') {
    loadAlbum();
    loadAlbumPhotos();
  }
}, { immediate: true });

// 组件挂载后加载数据
onMounted(() => {
  loadAllPhotos();
});
</script>

<style scoped lang="scss">
.album-detail {
  display: flex;
  flex-direction: column;
  height: 100%;
  
  .detail-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    padding: 16px;
    border-bottom: 1px solid var(--el-border-color-light);
    
    .album-info {
      flex: 1;
      
      .album-title {
        display: flex;
        align-items: center;
        margin-bottom: 8px;
        
        .back-button {
          margin-right: 8px;
          padding: 4px;
        }
        
        h2 {
          margin: 0;
          font-size: 20px;
          font-weight: 500;
          color: var(--el-text-color-primary);
        }
      }
      
      .album-description {
        font-size: 14px;
        color: var(--el-text-color-regular);
        margin-bottom: 8px;
        max-width: 80%;
      }
      
      .album-meta {
        display: flex;
        gap: 16px;
        font-size: 12px;
        color: var(--el-text-color-secondary);
        
        .photo-count {
          font-weight: 500;
        }
      }
    }
    
    .album-actions {
      display: flex;
      gap: 8px;
    }
  }
  
  .detail-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    
    .photos-container {
      flex: 1;
      overflow-y: auto;
      padding: 16px;
      
      .photos-grid {
        display: grid;
        gap: 16px;
        
        .photo-item {
          background-color: var(--el-bg-color);
          border-radius: 8px;
          overflow: hidden;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
          transition: all 0.2s ease;
          cursor: pointer;
          border: 2px solid transparent;
          
          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
          }
          
          &.photo-selected {
            border-color: var(--el-color-primary);
          }
          
          .photo-thumbnail {
            position: relative;
            overflow: hidden;
            
            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }
            
            .photo-overlay {
              position: absolute;
              top: 8px;
              right: 8px;
              background-color: rgba(0, 0, 0, 0.5);
              border-radius: 4px;
              padding: 4px;
            }
          }
          
          .photo-info {
            padding: 8px;
            
            .photo-name {
              font-size: 12px;
              font-weight: 500;
              color: var(--el-text-color-primary);
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }
            
            .photo-date {
              font-size: 10px;
              color: var(--el-text-color-secondary);
              margin-top: 2px;
            }
          }
        }
      }
      
      .photos-list {
        .photo-list-item {
          display: flex;
          align-items: center;
          padding: 8px;
          border-radius: 8px;
          margin-bottom: 8px;
          background-color: var(--el-bg-color);
          box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
          transition: all 0.2s ease;
          cursor: pointer;
          border: 2px solid transparent;
          
          &:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
          }
          
          &.photo-selected {
            border-color: var(--el-color-primary);
          }
          
          .photo-thumbnail {
            position: relative;
            overflow: hidden;
            border-radius: 4px;
            margin-right: 12px;
            flex-shrink: 0;
            
            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }
            
            .photo-overlay {
              position: absolute;
              top: 4px;
              right: 4px;
              background-color: rgba(0, 0, 0, 0.5);
              border-radius: 4px;
              padding: 2px;
            }
          }
          
          .photo-details {
            flex: 1;
            
            .photo-name {
              font-size: 14px;
              font-weight: 500;
              color: var(--el-text-color-primary);
              margin-bottom: 4px;
            }
            
            .photo-meta {
              display: flex;
              gap: 12px;
              font-size: 12px;
              color: var(--el-text-color-secondary);
            }
          }
        }
      }
      
      .photos-masonry {
        display: flex;
        flex-wrap: wrap;
        gap: 16px;
        
        .photo-masonry-item {
          background-color: var(--el-bg-color);
          border-radius: 8px;
          overflow: hidden;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
          transition: all 0.2s ease;
          cursor: pointer;
          border: 2px solid transparent;
          
          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
          }
          
          &.photo-selected {
            border-color: var(--el-color-primary);
          }
          
          .photo-thumbnail {
            position: relative;
            width: 100%;
            height: calc(100% - 40px);
            overflow: hidden;
            
            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }
            
            .photo-overlay {
              position: absolute;
              top: 8px;
              right: 8px;
              background-color: rgba(0, 0, 0, 0.5);
              border-radius: 4px;
              padding: 4px;
            }
          }
          
          .photo-info {
            padding: 8px;
            height: 40px;
            
            .photo-name {
              font-size: 12px;
              font-weight: 500;
              color: var(--el-text-color-primary);
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }
            
            .photo-date {
              font-size: 10px;
              color: var(--el-text-color-secondary);
              margin-top: 2px;
            }
          }
        }
      }
    }
    
    .empty-photos {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;
    }
  }
}

.album-detail-empty {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

// 响应式设计
@media (max-width: 768px) {
  .album-detail {
    .detail-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 12px;
      
      .album-info {
        .album-meta {
          flex-direction: column;
          gap: 4px;
        }
      }
      
      .album-actions {
        width: 100%;
        justify-content: flex-end;
      }
    }
    
    .detail-content {
      .photos-container {
        padding: 8px;
        
        .photos-grid {
          gap: 8px;
        }
      }
    }
  }
}
</style>